import type { Component } from 'vue';

import type { Recordable } from '@vben/types';

import { defineComponent, getCurrentInstance, h, ref } from 'vue';

import { $t } from '@vben/locales';
// 添加组件处理自动完成的默认行为
export const withDefaultAutocomplete = <T extends Component>(
  component: T,
  componentProps: Recordable<any> = {},
) => {
  return defineComponent({
    name: component.name,
    inheritAttrs: false,
    setup: (props: any, { attrs, expose, slots }) => {
      // 默认配置
      const defaults = {
        clearable: true,
        placeholder: $t('ui.placeholder.input'),
        highlightFirstItem: true,
        ...componentProps,
      };

      // 定义 timeout 变量，用于防抖
      let timeout: null | ReturnType<typeof setTimeout> = null;

      // 处理异步方法的防抖
      const debouncedFetch = (query: string, cb: (data: any[]) => void) => {
        if (props.fetchSuggestions) {
          const debounceTime = props.debounce ?? 300;

          // 清除之前的定时器
          if (timeout) {
            clearTimeout(timeout);
            timeout = null;
          }

          timeout = setTimeout(() => {
            props.fetchSuggestions(query, cb);
          }, debounceTime);
        }
      };

      // 暴露组件方法
      const innerRef = ref();
      const publicApi: Recordable<any> = {};
      expose(publicApi);
      const instance = getCurrentInstance();
      instance?.proxy?.$nextTick(() => {
        for (const key in innerRef.value) {
          if (typeof innerRef.value[key] === 'function') {
            publicApi[key] = innerRef.value[key];
          }
        }
      });

      return () =>
        h(
          component,
          {
            ...defaults,
            ...props,
            ...attrs,
            ref: innerRef,
            onFetchSuggestions: debouncedFetch,
          },
          slots,
        );
    },
  });
};
